/**
 * @file 登录页
 * @date 2025/10/24 12:46:49
 * @author lyqjob@yeah.net
 */

import { useState, useEffect } from 'react';
import { LockOutlined, UserOutlined, SafetyCertificateOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, message, Flex, Row ,Col} from "antd";
import { useDispatch } from 'react-redux'
import { useNavigate } from "react-router-dom";
import { login, setmenus, setpermissions, setasyncfiles, setsessionid } from "@/store/reducers/global";
import { getMenusTree } from "@/utils/utils";
import { adminApi } from "@/services/admin";
import logo from "@/static/images/logo.png"

import styles from "./index.less";

const Login = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [loading, setLoading] = useState(false)
    const [captcha, setCaptcha] = useState({});
    const [access_type, setAccessType] = useState('PC');
    const [form] = Form.useForm();

    const onFinish = async (values) => {
        values.captchaId = captcha.captchaId;
        setLoading(true)
        const [, res] = await adminApi.login(values)
        if (res?.code === 200 && res?.data) {
            const { menus, permissions, userinfo, accessToken, refreshToken ,sessionId} = res.data;
            const flatFiles = menus.filter(item => item.node_type !== 1 && item.component_path)
                .map(item => ({
                    path: item.route_path,
                    filepath: item.component_path,
                    title: item.name
                }));


            const treeMenus = getMenusTree(menus);

            // 存储会话id
            dispatch(setsessionid(sessionId));
            // 存储用户信息
            dispatch(login({ userinfo, accessToken, refreshToken }));
            // 存储菜单信息
            dispatch(setmenus(treeMenus));
            // 存储按钮权限信息
            dispatch(setpermissions(permissions || []));
            // 存储动态加载页面信息
            dispatch(setasyncfiles(flatFiles));

            message.success("登录成功", 1, () => {
                setLoading(false)
                navigate("/", { replace: true });
            });
        } else {
            // 清除原有form字段
            form.resetFields();
            // 重置验证码
            getCaptcha()
            setLoading(false)
        }

    };

    useEffect(() => {
        getCaptcha()
    }, [])


    const getCaptcha = async () => {
        const [, res] = await adminApi.getCaptcha()
        if (res) {
            setCaptcha(res.data)
        }
    }

    useEffect(() => {
        let random= Math.floor(Math.random() * (5 - 1 + 1) + 1);
        form.setFieldsValue({
            username: `admin${random}`,
        })
    }, []);


    useEffect(() => {
        if (window.innerWidth < 900) {
            setAccessType('MOBILE')
        } else {
            setAccessType('PC')
        }
    }, [])

    return (
        <div className={styles.container}>
             <div className={styles.loginbox}>

                {
                    access_type === 'PC' && (
                        <div className={styles.leftbox}>
                            <h2>欢迎登录 WL - Admin </h2>
                            <p>WL-Admin 是基于 NodeJs + Express + MySQL + Redis +  React + Antd + Webpack 构建的中后台管理系统</p>
                            <p>提供基础的后台管理系统功能，JWT认证，双Token无感刷新，全局错误捕获降级，RBAC0 + 权限层级 + 数据范围权限管控，实现菜单及按钮API权限，SSE通信，缓存管理、自动编码、日志管理等</p>
                        </div>
                    ) 
                }
                
                <Form
                    form={form}
                    name="login"
                    initialValues={{ remember: true, username: 'admin', password: '123456' }}
                    style={{ maxWidth: 800 }}
                    onFinish={onFinish}
                    className={styles.formbox}
                >
                    <div className={styles.header}>
                        <img src={logo} alt="logo" />
                        <h2>WL 管理系统</h2>
                    </div>
                    <Form.Item

                        name="username"
                        rules={[{ required: true, message: "请输入账号!" }]}
                    >
                        <Input style={{ height: 50 }} size="large" prefix={<UserOutlined />} placeholder="用户名" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        defaultValue="password"
                        rules={[{ required: true, message: "请输入密码!" }]}
                    >
                        <Input
                            prefix={<LockOutlined />}
                            size="large"
                            style={{ height: 50 }}
                            type="password"
                            placeholder="密码"
                        />
                    </Form.Item>

                    <Form.Item style={{ marginBottom: 0 }}>
                        <Flex justify="space-between" align="center">

                            <Form.Item
                                name="captcha"
                                rules={[{ required: true, message: "请输入验证码!" }]}
                            >
                                <Input
                                    style={{ height: 50 }}
                                    size="large"
                                    prefix={<SafetyCertificateOutlined />}
                                    maxLength={4}
                                    placeholder="验证码"
                                />

                            </Form.Item>
                            <div onClick={() => { getCaptcha() }} className={styles.captchaimg} dangerouslySetInnerHTML={{ __html: captcha?.captchaImage }} />
                        </Flex>
                    </Form.Item>



                    <Form.Item>
                        <Flex justify="space-between" align="center">
                            <Form.Item name="remember" valuePropName="checked" noStyle>
                                <Checkbox>记住密码</Checkbox>
                            </Form.Item>
                            {/* <a href="">忘记密码</a> */}
                        </Flex>
                    </Form.Item>

                    <Form.Item>
                        <Button style={{ height: 50 }} block type="primary" htmlType="submit" loading={loading}>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};
export default Login;
